<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="header-background"></div>
        <div class="avatar-section">
          <div class="avatar-uploader" @click="triggerFileInput" @dragover.prevent="handleDragOver"
            @drop.prevent="handleDrop" :class="{ 'dragover': isDragover, 'uploading': isUploading }">
            <div class="avatar-wrapper">
              <img v-if="form.avatar_url" :src="form.avatar_url" class="avatar">
              <div v-else class="avatar-placeholder">
                <el-icon :size="40" color="#10b981">
                  <UserCircle />
                </el-icon>
              </div>

              <div class="upload-mask" v-show="!isUploading">
                <el-icon :size="24" color="white">
                  <Camera />
                </el-icon>
                <span class="mask-text">{{ dragText }}</span>
              </div>

              <div class="upload-progress" v-if="isUploading">
                <el-progress type="circle" :percentage="uploadProgress" :width="80" color="#10b981" />
              </div>
            </div>

            <input type="file" ref="fileInput" accept="image/*" class="hidden-input" @change="handleFileSelect" />
          </div>
          <h3 class="avatar-title">{{ form.username || '点击上传头像' }}</h3>
          <div class="user-status">
            <span class="status-badge">
              <el-icon><CheckCircle /></el-icon>
              已认证用户
            </span>
          </div>
        </div>
      </div>

      <div class="profile-tabs">
        <div class="tab active">个人资料</div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" label-position="top" class="elegant-form">
        <!-- 表单内容 -->
        <div class="form-content">
          <div class="form-section">
            <h4 class="section-title">基本信息</h4>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入2-12位字符" clearable>
                <template #prefix>
                  <el-icon class="input-icon"><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" type="email" placeholder="name@example.com" clearable>
                <template #prefix>
                  <el-icon class="input-icon"><Mail /></el-icon>
                </template>
                <template #append>
                  <el-button type="success" plain @click="handleVerifyEmail" :disabled="form.email_verified" class="verify-btn">
                    {{ form.email_verified ? '已验证' : '验证邮箱' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-section">
            <h4 class="section-title">个人简介</h4>
            
            <el-form-item prop="bio">
              <el-input v-model="form.bio" type="textarea" :rows="4" placeholder="介绍一下你自己吧～" maxlength="500"
                show-word-limit />
            </el-form-item>
          </div>

          <div class="form-actions">
            <el-button type="primary" class="submit-btn" @click="submitForm" :loading="submitting">
              <el-icon :size="18" class="mr-2">
                <Save />
              </el-icon>
              保存修改
            </el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElProgress } from 'element-plus'
import { 
  Save, 
  Camera, 
  User, 
  Mail, 
  CheckCircle, 
  UserCircle
} from 'lucide-vue-next'
import network from '../api/index'
import { useStore } from '../store'

const store = useStore()
const user = store.getUserInfo()
const { communityApi, userApi, request, uploadApi } = network

// 表单数据
const form = ref({
  id: user.id,
  avatar_url: user.avatar_url,
  username: user.username,
  email: user.email,
  bio: user.bio,
  email_verified: true // 假设已验证
})

// 上传相关状态
const fileInput = ref(null)
const isUploading = ref(false)
const uploadProgress = ref(0)
const isDragover = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 12, message: '长度在2-12个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  bio: [
    { max: 500, message: '简介不能超过500字', trigger: 'blur' }
  ]
}

// 计算属性
const dragText = computed(() => {
  if (isUploading.value) return '上传中...'
  return isDragover.value ? '释放上传' : '更换头像'
})

// 触发文件选择
const triggerFileInput = () => {
  if (!isUploading.value) {
    fileInput.value.click()
  }
}

// 处理文件选择
const handleFileSelect = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  handleUpload(file)
}

// 处理拖放
const handleDragOver = () => {
  if (!isUploading.value) {
    isDragover.value = true
  }
}

const handleDrop = (e) => {
  isDragover.value = false
  const file = e.dataTransfer.files[0]
  if (file) handleUpload(file)
}

// 处理上传
const handleUpload = async (file) => {
  try {
    isUploading.value = true
    uploadProgress.value = 0
    
    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += 10
      }
    }, 300)
    
    const formData = new FormData();
    formData.append('avatar', file, file.name); 
    const { data } = await request(uploadApi.userAvatar, formData, 'POST')
    
    clearInterval(progressInterval)
    uploadProgress.value = 100
    
    setTimeout(() => {
      form.value.avatar_url = data.url;
      isUploading.value = false
    }, 500)
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    isUploading.value = false
    ElMessage.error('上传失败，请重试')
    console.error('上传错误详情:', {
      status: error.response?.status,
      data: error.response?.data
    });
  }
}

// 邮箱验证
const handleVerifyEmail = async () => {
  try {
    ElMessage.success('验证邮件已发送，请查收')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发送失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    const { data } = await request(userApi.profile, form.value, 'PUT')
    ElMessage.success('个人资料已更新')
    form.value = data
    store.setUser(data)
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '修改失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped lang="scss">
$primary-color: #10b981;
$primary-light: #d1fae5;
$primary-dark: #059669;
$secondary-color: #3b82f6;
$text-color: #1f2937;
$text-light: #6b7280;
$border-color: #e5e7eb;
$background-color: #f9fafb;
$card-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);

.profile-container {
  max-width: 800px;
  margin: 30px auto;
  padding: 0 20px;
  animation: fadeIn 0.5s ease;

  @media (max-width: 768px) {
    margin: 20px auto;
    padding: 0 15px;
  }
}

.profile-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: $card-shadow;
  border: none;
  
  :deep(.el-card__body) {
    padding: 0;
  }
}

.profile-header {
  position: relative;
  padding-top: 80px;
  padding-bottom: 30px;
  
  .header-background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 120px;
    background: linear-gradient(135deg, $primary-color, $secondary-color);
    z-index: 0;
  }
}

.avatar-section {
  position: relative;
  z-index: 1;
  text-align: center;
  
  .avatar-uploader {
    position: relative;
    display: inline-block;
    border: 4px solid white;
    border-radius: 50%;
    transition: all 0.3s ease;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    
    &.dragover {
      border-color: $primary-light;
      box-shadow: 0 0 0 4px rgba($primary-color, 0.2);
    }
    
    &.uploading {
      cursor: not-allowed;
    }
    
    .hidden-input {
      display: none;
    }
    
    .avatar-wrapper {
      position: relative;
      width: 120px;
      height: 120px;
      border-radius: 50%;
      overflow: hidden;
      
      @media (max-width: 768px) {
        width: 100px;
        height: 100px;
      }
      
      .avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
      }
      
      .avatar-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: $primary-light;
      }
      
      .upload-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: white;
        opacity: 0;
        transition: opacity 0.3s ease;
        
        .mask-text {
          margin-top: 8px;
          font-size: 12px;
          font-weight: 500;
        }
      }
      
      .upload-progress {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.9);
      }
    }
    
    &:hover:not(.uploading) {
      .upload-mask {
        opacity: 1;
      }
      
      .avatar {
        transform: scale(1.05);
      }
    }
  }
  
  .avatar-title {
    margin-top: 16px;
    font-size: 22px;
    font-weight: 600;
    color: $text-color;
    
    @media (max-width: 768px) {
      font-size: 18px;
      margin-top: 12px;
    }
  }
  
  .user-status {
    margin-top: 8px;
    
    .status-badge {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      padding: 4px 10px;
      background-color: $primary-light;
      color: $primary-dark;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
      
      .el-icon {
        font-size: 14px;
      }
    }
  }
}

.profile-tabs {
  display: flex;
  padding: 0 30px;
  border-bottom: 1px solid $border-color;
  margin-bottom: 20px;
  justify-content: center;
  @media (max-width: 768px) {
    padding: 0 15px;
    overflow-x: auto;
    
    &::-webkit-scrollbar {
      display: none;
    }
  }
  
  .tab {
    padding: 16px 20px;
    font-weight: 500;
    color: $text-light;
    cursor: pointer;
    position: relative;
    white-space: nowrap;
    
    @media (max-width: 768px) {
      padding: 12px 15px;
      font-size: 14px;
    }
    
    &.active {
      color: $primary-color;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background-color: $primary-color;
      }
    }
    
    &:hover:not(.active) {
      color: $text-color;
    }
  }
}

.elegant-form {
  padding: 0 30px 30px;
  
  @media (max-width: 768px) {
    padding: 0 15px 20px;
  }
}

.form-content {
  .form-section {
    margin-bottom: 24px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: $text-color;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px dashed $border-color;
    }
  }
  
  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 500;
    color: $text-color;
    padding-bottom: 4px;
  }
  
  .input-icon {
    color: $text-light;
    font-size: 16px;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    background-color: $background-color;
    box-shadow: 0 0 0 1px $border-color;
    transition: all 0.2s ease;
    
    &:hover {
      box-shadow: 0 0 0 1px $primary-color;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px $primary-color, 0 0 0 4px rgba($primary-color, 0.1) !important;
    }
  }
  
  :deep(.el-textarea__inner) {
    border-radius: 8px;
    background-color: $background-color;
    box-shadow: 0 0 0 1px $border-color;
    transition: all 0.2s ease;
    padding: 12px;
    
    &:hover {
      box-shadow: 0 0 0 1px $primary-color;
    }
    
    &:focus {
      box-shadow: 0 0 0 1px $primary-color, 0 0 0 4px rgba($primary-color, 0.1);
    }
  }
  
  .verify-btn {
    border-color: $primary-color;
    color: $primary-color;
    
    &:hover {
      background-color: rgba($primary-color, 0.05);
    }
    
    &:disabled {
      color: $text-light;
      border-color: $border-color;
      background-color: $background-color;
    }
  }
  
  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 30px;
    
    @media (max-width: 768px) {
      flex-direction: column;
      gap: 8px;
    }  
    .submit-btn {
      min-width: 140px;
      background-color: $primary-color;
      border-color: $primary-color;
      transition: all 0.2s ease;
      
      @media (max-width: 768px) {
        order: 1;
        min-width: 100%;
      }
      
      &:hover {
        background-color: $primary-dark;
        border-color: $primary-dark;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba($primary-color, 0.3);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>

